package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xiaobai
 * @create 2024-03-19 16:50
 */

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /*
    * 统计指定时间区间内的营业额
    * */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //存放每天的日期
        List<LocalDate> dateList=new ArrayList<>();

        //将第一天先存入集合中
        dateList.add(begin);
        //通过循环 将从第一天一直到最后一天依次存入集合中
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);

        }

        //存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();

        //遍历日期集合 将每天 取出每天的一开始和每天的结束
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);


            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover=orderMapper.sumByMap(map);
            //如果turnover返回的是空 则转为0.0  否则直接赋值
            turnover=turnover==null?0.0:turnover;
            turnoverList.add(turnover);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /*
    * 统计指定时间区间内的用户数据
    * */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //存放日期  dateList
        List<LocalDate> dateList= new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);

        }
        //存放每天新增的用户数量
        List<Integer> newUserList=new ArrayList<>();
        //存放每天的总用户量
        List<Integer> totalUserList=new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime=LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date,LocalTime.MAX);

            //集合中的key要和xml中对应
            Map map=new HashMap();
            map.put("end",endTime);
            //获取每天的总用户量
            Integer totalUser = userMapper.countByMap(map);

            map.put("begin",beginTime);
            //获取每天新增的用户量
            Integer newUser = userMapper.countByMap(map);

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }


        //封装结果数据
        return  UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();

    }


    /*
    * 统计指定时间区间内的订单数据
    * */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //存放begin到end之间的每天的对应日期
        List<LocalDate> dateList=new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        //存放每天的订单总数
        List<Integer> orderCountList=new ArrayList<>();
        //存放每天的有效订单数
        List<Integer> validOrderCountList=new ArrayList<>();

        //遍历集合  查询每天的有效订单 和 订单总数
        for (LocalDate date : dateList) {
            LocalDateTime beginTime=LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date,LocalTime.MAX);
            //查询每天的订单总数
            Integer orderCount = getOrderCount(beginTime, endTime, null);

            //查询每天的有效订单总数
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);

        }

        //计算时间区间内的订单总数量
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //计算时间区间内的有效订单总数量
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //计算时间区间内的订单完成率  需要将Integer转成double   注意分母不为0
        Double orderCompletionRate=totalOrderCount==0?0.0:validOrderCount.doubleValue()/totalOrderCount;

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,"."))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();


    }

    private Integer getOrderCount(LocalDateTime begin,LocalDateTime end, Integer status){
        Map map=new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);

        return orderMapper.countByMap(map);
    }


    /*
     * 销量排名
     * */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime=LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(begin,LocalTime.MAX);

        //查询指定日期区间的销量前十 封装到集合中
        List<GoodsSalesDTO> salesTop10 =orderMapper.getSalesTop10(begin,end);
        //使用stream流 对销量前十的每个菜品 调用getName方法获取菜品名称  并重新封装到names集合中
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        //使用stream流 对销量前十的每个菜品 调用getNumber方法获取菜品名称  并重新封装到numbers集合中
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());


        //封装返回数据
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names,","))
                .numberList(StringUtils.join(numbers,","))
                .build();

    }

    /*
    * 导出运营数据报表
    * */
    public void getBusinessData(HttpServletResponse response) {
        //1.查询数据库 获得营业数据  ---查询最近30天的数据
        
        //设置起始日期
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //获取营业数据  接收参数精确到时间  需要转换
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2.通过POI 将数据写入到excel文件中
        InputStream in=this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的excel表格
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取sheet标签页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据：时间
            sheet.getRow(1).getCell(1).setCellValue("时间： "+dateBegin+" 至"+dateEnd);

            //写入第4行数据
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //写入第5行数据
            row=sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充订单明细  遍历30天  获得每天的订单数据
            for (int i = 0; i < 30; i++) {
                LocalDate date=dateBegin.plusDays(i);

                //查询某一天的营业额  传入当天的起始时间
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //从第8行开始 写入数据 i+8
                row=sheet.getRow(i+7);//获得某一行
                row.getCell(1).setCellValue(date.toString());     //写入日期
                row.getCell(2).setCellValue(businessDataVO.getTurnover());//营业额
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());//有效订单数
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());//订单完成率
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());//平均客单价
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());//新增用户
            }


            //3.使用输出流将Excel表格下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }



    }
}
